import socket
import threading
import time


class HttpSocket(object):
    def __init__(self):
        server_socket = socket.socket()
        server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
        server_socket.bind(("",8080))
        server_socket.listen(128)
        self.server_socket = server_socket

    def main(self):
        while True:
            new_socket, new_address = self.server_socket.accept()
            threading.Thread(target=self.func,args=(new_socket, new_address),daemon=True).start()

    @staticmethod
    def func(new_socket, new_address):
        print(f"{str(new_address)}已上线")
        recv_data = new_socket.recv(4096)
        if not recv_data:
            print(f"{str(new_address)}已下线")
        path_info = recv_data.decode().split(" ")[1]
        if path_info == "/":
            path_info = "/index.html"

        if path_info.endswith(".html"):
            env = {
                "PATH_INFO" : path_info
            }
            import Application_diango
            status,headers,response_body = Application_diango.app(env)
            response_data = "http/1.1" + status + "\r\n"
            for head in headers:
                response_data += "%s:%s\r\n\r\n" % head
            response_data += response_body
            new_socket.send(response_data.encode())
            new_socket.close()


        else:
            try:
                with open("./static" + path_info, "rb") as file:
                    file_data = file.read()
            except Exception as e:
                # 如果发生异常　执行这里
                with open("./static/404.html", "rb") as file:
                    file_data = file.read()
                http_response_data = "HTTP/1.1 404 Not Found\r\nServer: PWS1.0\r\n\r\n".encode() + file_data
            else:
            # 没有异常执行这里
            # 3.回复响应报文<HTTP响应报文>
                http_response_data = "HTTP/1.1 200 OK\r\nServer: PWS1.0\r\n\r\n".encode() + file_data

            finally:
                # 不管有没有异常　都执行这里
                new_socket.send(http_response_data)
                time.sleep(2)
        # 4.关闭和客户端关联的套接字　　－　短连接
                new_socket.close()

if __name__ == '__main__':
    http_socket = HttpSocket()
    http_socket.main()
